package com.wzh.glsc.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.product.config
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */

//加入让配置类生效的注解
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching //开启缓存配置
@Configuration //代表这是个配置类
public class MyRedisCacheConfig {

    //定义配置
    @Bean //注入到容器中
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        //拿到默认配置类，默认的配置类会判断容器中是否有自定义的，没有就用默认的
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //配置redis缓存key序列化方式，这里指定的是redis自己的序列化器
        config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //配置redis缓存value序列化方式,这里指定的redis下阿里jackson的json序列化器
        config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        //拿到配置文件类
        // 可以用@Autowired注解中容器中获取CacheProperties
        //也可以直接放入方法的参数中
        //从CacheProperties获取到配置文件中Redis配置 CacheProperties.Redis
        CacheProperties.Redis redis = cacheProperties.getRedis();
        //将配置文件中所有的配置都生效
        if (redis.getTimeToLive() != null) {
            config = config.entryTtl(redis.getTimeToLive());
        }
        if (redis.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redis.getKeyPrefix());
        }
        if (!redis.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redis.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
